package cn.xopencode.oss.dal.redis.dao;

import cn.xopencode.oss.dal.redis.RedisKeyConstants;
import cn.xopencode.oss.rpc.permission.dto.PermissionCheckDTO;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class OAuth2UserPositionPemissionDAO {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public PermissionCheckDTO get(String userID) {
        String redisKey = formatKey(userID);
        return JSON.parseObject(redisTemplate.opsForValue().get(redisKey), PermissionCheckDTO.class);
    }

    public void set(PermissionCheckDTO permissionCheckDO) {
        String redisKey = formatKey(permissionCheckDO.getUserId());
        redisTemplate.opsForValue().set(redisKey, JSON.toJSONString(permissionCheckDO), RedisKeyConstants.OAUTH2_USER_POSITION_PERMISSION.getTimeout());
    }

    public void delete(String accessToken) {
        String redisKey = formatKey(accessToken);
        redisTemplate.delete(redisKey);
    }

    private static String formatKey(String userId) {
        return String.format(RedisKeyConstants.OAUTH2_USER_POSITION_PERMISSION.getKeyTemplate(), userId);
    }

}
